package com.aorise.service.system;

import com.aorise.model.system.User;
import com.aorise.utils.excel.ExcelUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @Auther: zhouhao
 * @Date: 2019/5/27
 * @Description:
 */
public interface BaseService {

    /**
     * 获取登录用户信息
     * @return
     */
    default User getLoginUser(){
        return ((User) SecurityUtils.getSubject().getPrincipal());
    }

    /**
     * 判断更新 添加等操作是否成功
     * @param i
     * @return
     */
     default boolean getBoolean(int i) {
        boolean judge =false;
        if(i >= 1){
            judge = true;
        }
        return judge;
    }

    /**
     * bean 之间复制的辅助方法
     * @param source
     * @return
     */
    default String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for(PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     * 下载模板
     *
     * @param response
     */
    default void downloadBayonetTemplate(HttpServletResponse response, String templateName) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("template/" + templateName + ".xlsx");
            String filePath = classPathResource.getFile().getAbsolutePath();
            ExcelUtil.downloadFile(response, filePath, templateName, false);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
